package com.yzt.shiro;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;

import com.yzt.base.utils.ShiroUtils;


/**
 * @author Y <br>
 * @date 2020年11月26日 <br>
 *       <br>
 */
public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private DefaultWebSessionManager defaultWebSessionManager;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		System.out.println("-------获取权限列表-------");

		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		List<String> permissionList = new ArrayList<>();
		permissionList.add("tttt");
		authorizationInfo.addStringPermissions(permissionList);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String salt = "root";
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo("root", ShiroUtils.encode("root", salt),
				ByteSource.Util.bytes(salt), getName());
		return info;
	}

	public void clearAllCache() {
		Iterator<Session> iterator = defaultWebSessionManager.getSessionDAO().getActiveSessions().iterator();
		while (iterator.hasNext()) {
			Session session = iterator.next();
			PrincipalCollection principalCollection = (PrincipalCollection) session
					.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
			clearCachedAuthorizationInfo(principalCollection);
		}
	}

}
